//
//  CoreDataUtil.m
//  YiJuZhangShou
//
//  Created by 冷悦 on 16/3/7.
//  Copyright © 2016年 Uranus. All rights reserved.
//

#import <CoreData/CoreData.h>
#import "CoreDataUtil.h"
#import "UploadErrorLogsViewModel.h"
#import "UploadUserRecordsViewModel.h"
#import "MJExtension.h"

@interface CoreDataUtil()

@property (nonatomic, strong) UploadErrorLogsViewModel *uploadErrorLogsViewModel;
@property (nonatomic, strong) UploadUserRecordsViewModel *uploadUserRecordsViewModel;

@end

@implementation CoreDataUtil

static CoreDataUtil *_instance = nil;

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
@synthesize logs = _logs;
@synthesize errorLogs = _errorLogs;

#pragma mark - initialize
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _instance = [[CoreDataUtil alloc]init];
    });
    
    return _instance;
}

#pragma mark - Core Data stack
- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.uranus.YiJuZhangShou" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"YiJuZhangShou" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"YiJuZhangShou.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        DDLogInfo(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support
- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            DDLogInfo(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Public
- (void)deleteLogs:(LogType)logType{
    NSMutableArray *deleteArray;
    
    if (logType == CoreDataLog) {
        deleteArray = self.logs;
    } else if (logType == CoreDataErrorLog) {
        deleteArray = self.errorLogs;
    }
    
    if (deleteArray != nil) {
        for (LogDataObject *logDataObject in deleteArray) {
            [self.managedObjectContext deleteObject:logDataObject];
        }
        [deleteArray removeAllObjects];
        [self saveContext];
    }
}

- (void)uploadErrorLogs{
    if (self.errorLogs != nil) {
        NSMutableDictionary *postDic = [NSMutableDictionary dictionary];
        NSMutableArray *dataArray = [ErrorLogDataObject mj_keyValuesArrayWithObjectArray:self.errorLogs];
        [postDic setObject:dataArray forKey:@"data"];
        self.uploadErrorLogsViewModel.postObject = postDic;
        [self.uploadErrorLogsViewModel loadRequest];
    }
}

- (void)uploadUserRecords{
    if (self.logs != nil) {
        NSMutableDictionary *postDic = [NSMutableDictionary dictionary];
        NSMutableArray *dataArray = [LogDataObject mj_keyValuesArrayWithObjectArray:self.logs];
        [postDic setObject:dataArray forKey:@"data"];
        self.uploadUserRecordsViewModel.postObject = postDic;
        [self.uploadUserRecordsViewModel loadRequest];
    }
}

#pragma mark - Getters
- (NSMutableArray *)logs{
    if (_logs == nil) {
        NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"LogDataObject"];
        NSError *error;
        NSArray *result = [self.managedObjectContext executeFetchRequest:request error:&error];
        _logs = [NSMutableArray arrayWithArray:result];
    }
    
    return _logs;
}

- (NSMutableArray *)errorLogs{
    if (_errorLogs == nil) {
        NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"ErrorLogDataObject"];
        NSError *error;
        NSArray *result = [self.managedObjectContext executeFetchRequest:request error:&error];
        _errorLogs = [NSMutableArray arrayWithArray:result];
    }
    
    return _errorLogs;
}

- (UploadErrorLogsViewModel *)uploadErrorLogsViewModel{
    if (_uploadErrorLogsViewModel == nil) {
        _uploadErrorLogsViewModel = [UploadErrorLogsViewModel new];
    }
    return _uploadErrorLogsViewModel;
}

- (UploadUserRecordsViewModel *)uploadUserRecordsViewModel{
    if(_uploadUserRecordsViewModel == nil){
        _uploadUserRecordsViewModel = [UploadUserRecordsViewModel new];
    }
    return _uploadUserRecordsViewModel;
}

@end
